﻿using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;

namespace MyHelpers
{
    /// <summary>
    /// Excel操作帮助类
    /// </summary>
    public static class ExcelHelper
    {
        #region 文件整体

        /// <summary>将DataTable存入文件</summary>
        /// <param name="dtSource"></param>
        /// <param name="fileName"></param>
        /// <remarks>NPOI认为Excel的第一个单元格是：(0，0)</remarks>
        public static void ExportSlim(DataTable dtSource, string fileName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();
            //填充表头
            IRow dataRow = sheet.CreateRow(0);
            foreach (DataColumn column in dtSource.Columns)
            {
                dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
            }
            //填充内容
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
                }
            }
            //保存
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);
            }
            workbook.Close();
        }

        /// <summary>DataTable导出到Excel文件</summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="headerText">表头文本</param>
        /// <param name="fileName">保存位置</param>
        /// <returns></returns>
        public static bool Export(DataTable dtSource, string headerText, string fileName)
        {
            try
            {
                using (MemoryStream ms = Export(dtSource, headerText))
                {
                    using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(nameof(Export), ex, fileName);
                return false;
            }
            return true;
        }

        /// <summary>DataTable导出到Excel的MemoryStream</summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="headerText">表头文本</param>
        public static MemoryStream Export(DataTable dtSource, string headerText)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();

            #region 右击文件 属性信息
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "NPOI";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = "chenz"; //填加xls文件作者信息
                si.ApplicationName = "DailyReport系统"; //填加xls文件创建程序信息
                si.LastAuthor = "chenz"; //填加xls文件最后保存者信息
                si.Comments = "HeTao"; //填加xls文件作者信息
                si.Title = "DailyReport"; //填加xls文件标题信息

                si.Subject = "DailyReport";//填加文件主题信息
                si.CreateDateTime = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            //创建样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            ICellStyle cellDefStyle = workbook.CreateCellStyle();
            IFont fontDef = workbook.CreateFont();
            fontDef.FontHeightInPoints = 12;
            fontDef.Boldweight = (short)FontBoldWeight.Normal;
            cellDefStyle.SetFont(fontDef);
            cellDefStyle.BorderBottom = BorderStyle.Thin;
            cellDefStyle.BorderLeft = BorderStyle.Thin;
            cellDefStyle.BorderRight = BorderStyle.Thin;
            cellDefStyle.BorderTop = BorderStyle.Thin;
            cellDefStyle.WrapText = true;

            //取得列宽
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName).Length;
                arrColWidth[item.Ordinal] = (int)(arrColWidth[item.Ordinal] * 1.5);
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            for (int i = 0; i < arrColWidth.Length; i++)    //xls的最大列宽为255，保守设为250（这里的修改主要为列头宽度设置服务）
            {
                if (arrColWidth[i] > 250)
                {
                    arrColWidth[i] = 250;
                }
            }
            int rowIndex = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表，填充表头，填充列头，样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }

                    bool haveHeader = !string.IsNullOrEmpty(headerText);
                    #region 表头及样式
                    {
                        if (haveHeader)
                        {
                            IRow headerRow = sheet.CreateRow(0);
                            headerRow.HeightInPoints = 25;
                            headerRow.CreateCell(0).SetCellValue(headerText);

                            ICellStyle headStyle = workbook.CreateCellStyle();
                            headStyle.Alignment = HorizontalAlignment.Center;
                            headStyle.VerticalAlignment = VerticalAlignment.Center;
                            IFont font = workbook.CreateFont();
                            font.FontHeightInPoints = 20;
                            font.Boldweight = 700;
                            headStyle.SetFont(font);
                            headerRow.GetCell(0).CellStyle = headStyle;
                            sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                        }
                    }
                    #endregion


                    #region 列头及样式
                    {
                        IRow headerRow = sheet.CreateRow(haveHeader ? 1 : 0);
                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        headStyle.VerticalAlignment = VerticalAlignment.Center;
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 18;
                        font.Boldweight = (short) FontBoldWeight.Bold;
                        headStyle.SetFont(font);
                        headStyle.FillPattern = FillPattern.SolidForeground;
                        headStyle.FillForegroundColor = HSSFColor.PaleBlue.Index;
                        headStyle.BorderBottom = BorderStyle.Thin;
                        headStyle.BorderLeft = BorderStyle.Thin;
                        headStyle.BorderRight = BorderStyle.Thin;
                        headStyle.BorderTop = BorderStyle.Thin;
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }
                    }
                    #endregion

                    rowIndex = haveHeader ? 2 : 1;
                }
                #endregion


                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell newCell = dataRow.CreateCell(column.Ordinal);
                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型
                            newCell.SetCellValue(drValue);

                            newCell.CellStyle = cellDefStyle;//格式化显示
                            break;
                        case "System.DateTime"://日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);

                            newCell.CellStyle = cellDefStyle;//格式化显示
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);

                            newCell.CellStyle = cellDefStyle;//格式化显示
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);

                            newCell.CellStyle = cellDefStyle;//格式化显示
                            break;
                        case "System.DBNull"://空值处理
                            newCell.SetCellValue("");

                            newCell.CellStyle = cellDefStyle;//格式化显示
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }
            //
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            workbook.Close();
            return ms;
        }

        /// <summary>用于Web导出</summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="headerText">表头文本</param>
        /// <param name="fileName">文件名</param>
        public static void ExportByWeb(DataTable dtSource, string headerText, string fileName)
        {
            HttpContext curContext = HttpContext.Current;

            // 设置编码和附件格式
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));

            curContext.Response.BinaryWrite(Export(dtSource, headerText).GetBuffer());
            curContext.Response.End();
        }

        /// <summary>读取excel，默认第一行为标头</summary>
        /// <param name="fileName">excel文档路径</param>
        /// <returns></returns>
        public static DataTable Import(string fileName)
        {
            DataTable dt = new DataTable();

            IWorkbook workbook;
            using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                if (fileName.ToUpper().EndsWith("XLSX"))
                    workbook = new XSSFWorkbook(file);
                else
                    workbook = new HSSFWorkbook(file);
            }
            ISheet sheet = workbook.GetSheetAt(0);
            // ReSharper disable once UnusedVariable
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    ICell cell = row.GetCell(j);
                    if (cell != null)
                    {
                        if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
                        {
                            dataRow[j] = cell.DateCellValue.ToString("yyyy/MM/dd");
                        }
                        else
                        {
                            dataRow[j] = cell.ToString();
                        }
                    }
                }

                dt.Rows.Add(dataRow);
            }
            return dt;
        }

        #endregion

        #region 单元格操作







        #endregion
    }
}
